package br.com.srv.componentes.login.dao.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import br.com.srv.model.ClienteTO;

public class LoginJDBCDAOImpl extends SimpleJdbcDaoSupport implements LoginJDBCDAO {

	@SuppressWarnings("unchecked")
	public ClienteTO efetuarLogin(ClienteTO clienteTO) {
		
		ClienteTO result = null;

		String query = "select usr_id, cli_id, tus_cod, usr_lgn from usuario, tp_usr where usr_lgn = ? and usr_pwd = ? and tp_usr.tus_id = usuario.tus_id";
		Object params[] = {clienteTO.getLogin(), clienteTO.getPassword()};
		
		List<ClienteTO> clientes = getJdbcTemplate().query(query, params, new ClienteTOMapper());
		
		if (clientes != null && !clientes.isEmpty()) {
			result = clientes.get(0);
		}
		
		return result;
	}
	
	public List<Map<String, String>>  pegarVeiculosByUsuarioId(Integer clienteId) {
		List<Map<String, String>>  veiculos = null;
		
		String query = "select distinct vei_id, vei_dsc from veiculo v, cliente c where v.cli_id = ? OR (c.cli_id = v.cli_id AND c.cli_mae = ?)";
		Object params[] = {clienteId,clienteId};
		
		veiculos = getJdbcTemplate().query(query, params, new VeiculoMapMapper());
		
		return veiculos;
	}
	
	public void atualizar(ClienteTO clienteTO) {
		String sql = "update usuario set usr_pwd = '" + clienteTO.getPassword()
			+ "' where usr_lgn = '" + clienteTO.getLogin() + "'";
		getJdbcTemplate().execute(sql);
	}
	
    private static class VeiculoMapMapper implements RowMapper {

		public Map<String, String> mapRow(ResultSet rs, int rowNum) throws SQLException {
			Map<String, String> mapaVeiculo = new HashMap<String, String>();
			mapaVeiculo.put("ID", rs.getString("vei_id"));
			mapaVeiculo.put("DESC", rs.getString("vei_dsc"));
			return mapaVeiculo;
		}

    }

    private static class ClienteTOMapper implements RowMapper {

		public ClienteTO mapRow(ResultSet rs, int rowNum) throws SQLException {
			ClienteTO clienteTO = new ClienteTO();
			clienteTO.setId(rs.getInt("cli_id"));
			clienteTO.setUserId(rs.getInt("usr_id"));
			clienteTO.setTipoCliente(rs.getInt("tus_cod"));
			clienteTO.setLogin(rs.getString("usr_lgn"));
			return clienteTO;
		}

    }

}
